package com.zjzywl.smoke.controller;

import java.io.BufferedInputStream;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zjzywl.smoke.config.BaseDataConfig;
import com.zjzywl.smoke.manager.AlarmManager;
import com.zjzywl.smoke.repository.AlarmRepository;
import com.zjzywl.smoke.repository.AlarmTypeRepository;
import com.zjzywl.smoke.repository.DeviceRepository;
import com.zjzywl.smoke.repository.DeviceStatusHistoryRepository;
import com.zjzywl.smoke.repository.DeviceStatusRepository;
import com.zjzywl.smoke.util.MQWebSocket;
import com.zjzywl.smoke.entity.Alarm;
import com.zjzywl.smoke.entity.AlarmType;
import com.zjzywl.smoke.entity.Device;
import com.zjzywl.smoke.entity.DeviceStatus;
import com.zjzywl.smoke.entity.DeviceStatusHistory;

//@WebServlet(description = "post get", urlPatterns = { "/siterwell"} )
@RestController

public class SiterwellController extends HttpServlet {
	@Autowired
	private DeviceRepository deviceRepository;

	@Autowired
	private DeviceStatusRepository deviceStatusRepository;

	@Autowired
	private DeviceStatusHistoryRepository deviceStatusHistoryRepository;

	@Autowired
	private AlarmTypeRepository alarmTypeRepository;

	@Autowired
	private AlarmRepository alarmRepository;

	@Autowired
	private AlarmManager alarmManager;
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SiterwellController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@RequestMapping(value = "/siterwell")
	 
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String[] tp = new String[3];
		tp[0] = request.getParameter("msg");
		tp[1] = request.getParameter("nonce");
		tp[2] = request.getParameter("signature");
		PrintWriter out = response.getWriter();
		out.print(tp[0]);
		out.close();
		out = null;
		response.getWriter().append("Served at: ").append(tp[0]);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@RequestMapping(value = "/byuser")
	 
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// doGet(request, response);
		InputStream result = new BufferedInputStream(request.getInputStream());
		ByteArrayOutputStream sout = new ByteArrayOutputStream();
		int b = 0;
		while ((b = result.read()) != -1) {
			sout.write(b);

		}
		byte[] temp = sout.toByteArray();
		String re = new String(temp, "UTF-8");

		/*
		 * 接收设备状态数据 DevEUI:设备唯一编号 status:设备状态 returnTime:上报时间 data:上报的原始串数据
		 *
		 * 1、筛选数据 2、存储记录到实时数据表 3、存储记录到历史记录表 4、通过websocket同步数据
		 */
		JSONObject json = (JSONObject) JSON.parse(re);
		String Str = json.getString("service");
		JSONObject jsonObject = (JSONObject) JSON.parse(Str);
		String string = jsonObject.getString("data");
		JSONObject Payload = (JSONObject) JSON.parse(string);
		String devCode = Payload.getString("IMEI");
		Device device = deviceRepository.findByDeviceCode(devCode);
		if (device == null) {
			System.out.println("找不到编号为：[" + devCode + "]的设备");
			return;
		}
		int status = Integer.parseInt(Payload.getString("DEVICESTATUS"));
		if (status == 5) {
			status = 3;
		}
		System.out.println("收到编号为:[" + devCode + "]设备状态：" + status);
		// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// Date time = format.parse(returnTime); //上报上来的时间数据很多不正常，因此注释

		// 保存历史状态信息
		DeviceStatusHistory dsh = new DeviceStatusHistory();
		dsh.setDevCode(devCode);
		dsh.setDevice(device);
		dsh.setHumidity("0");
		dsh.setTemperature1("0");
		dsh.setReturnTime(new Date());
		dsh.setStatus(status);
		dsh.setLight("0");
		dsh.setVoltage("0");
		dsh.setSpace("0");
		dsh.setTemperature("0");
		deviceStatusHistoryRepository.save(dsh);

		// 2为静音操作，9为自检操作，不是特定状态，因此只是历史信息表中存储，不作为实时状态信息存储到状态表及修改地图当前状态
		if ((status == BaseDataConfig.GS517_SMOKE_DS_SILENCE) || (status == BaseDataConfig.GS517_SMOKE_DS_SELFTEST)) {
			return;
		}

		// 保存状态信息
		DeviceStatus ds = new DeviceStatus();
		ds.setDevCode(devCode);
		ds.setDevice(device);
		ds.setHumidity("0");
		ds.setTemperature1("0");
		ds.setReturnTime(new Date());
		ds.setStatus(status);
		ds.setLight("0");
		ds.setVoltage("0");
		ds.setSpace("0");
		ds.setTemperature("0");
		// ds.setData(data);

		// 更新状态信息
		deviceStatusRepository.deleteByDevCode(devCode);
		deviceStatusRepository.save(ds);
		// BaseDataConfig.GS517_SMOKE_DS_FIRE;
		// 设备报警编码转为系统报警编码
		String alarmCode = "";
		Integer alarmId = 0;
		switch (status) {
		case 1: {
			alarmCode = BaseDataConfig.ALARM_FIRE;
			break;
		}
		case 3: {
			alarmCode = BaseDataConfig.ALARM_TROUBLE;
			break;
		}
		case 4: {
			alarmCode = BaseDataConfig.ALARM_LOW;
			break;
		}
		case 7: {
			// 设置该设备所有报警信息结束时间，并从列表中移除
			alarmManager.backToNormal(devCode);
		}
		default:
			alarmCode = "";
		}

		// 如果是报警数据，保存报警数据
		if (alarmCode != "") {
			AlarmType alarmType = alarmTypeRepository.findByAlarmCode(alarmCode);
			if (alarmType == null) {
				System.out.println("找不到编号为[" + alarmCode + "]的报警类型");
				return;
			}
			Alarm alarm = new Alarm(device, alarmType);
			alarm.setAddress(device.getAddress());
			alarm.setDevice(device);
			alarm.setBeginTime(new Date());
			alarm.setDisposeStatus(0);
			Alarm am = alarmRepository.save(alarm);
			alarmId = am.getAlarmId();

			// 加入到报警队列中
			alarmManager.occurAlarm(am);
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		java.util.Date date = new java.util.Date();
		String strDate = sdf.format(date);

		// String count =
		// deviceStatusRepository.getDSCountByUserAndDeviceCode(MQWebSocket.,
		// deviceCode)

		// 发送信息
		MQWebSocket.sendInfo(BaseDataConfig.CMD_SENDALARM + "," + ds.getDevice().getDevCode() + ","
				+ ds.getStatus().toString() + "," + ds.getStatusStr() + "," + ds.getDevice().getLatitude() + ","
				+ ds.getDevice().getLongitude() + "," + ds.getDevice().getDeviceName() + ","
				+ ds.getDevice().getAddress() + "," + strDate + "," + ds.getDevice().getLinkMain1() + ","
				+ ds.getDevice().getLinkPhone1() + "," + ds.getDevice().getLinkMain2() + ","
				+ ds.getDevice().getLinkPhone2() + "," + ds.getDevice().getLinkMain3() + ","
				+ ds.getDevice().getLinkPhone3() + "," + ds.getDevice().getLinkMain4() + ","
				+ ds.getDevice().getLinkPhone4() + "," + alarmId.toString());
	}

}
